  <!-- 添加车次库存 -->
<template>
  <div
    class="train_inventory_insert"
    v-if="!appStore.isPhone">
    <el-card>
      <el-button
        v-if="!route.query.id"
        @click="selectPurchaseBatch"
        class="select_order">
        选择订单
      </el-button>
      <el-descriptions
        :column="appStore.column"
        border>
        <el-descriptions-item label="主体公司名称"> {{ viewData.baseCompanySimpleName }} </el-descriptions-item>
        <el-descriptions-item label="米厂名称"> {{ viewData.baseRiceBarnSimpleName }} </el-descriptions-item>
        <el-descriptions-item label="采购订单名称"> {{ viewData.purchaseOrderName }} </el-descriptions-item>
        <el-descriptions-item label="订单编号"> {{ viewData.purchaseOrderNumber }} </el-descriptions-item>
        <el-descriptions-item label="采购时间"> {{ formatDate(viewData.purchaseDate) }} </el-descriptions-item>
        <el-descriptions-item label="资金仓库名称"> {{ viewData.baseCapitalWarehouseName }} </el-descriptions-item>
        <el-descriptions-item label="采购总吨数"> {{ viewData.purchaseSumTon }} </el-descriptions-item>
        <el-descriptions-item label="到货吨数"> {{ viewData.tonnageArrived }} </el-descriptions-item>
        <el-descriptions-item
          label="进度"
          v-if="viewData.purchaseSumTon >= 0 && viewData.tonnageArrived >= 0">
          <el-progress
            :text-inside="true"
            :stroke-width="24"
            :percentage="(viewData.tonnageArrived / viewData.purchaseSumTon) * 100 > 100 ? 100 : parseInt(viewData.tonnageArrived / viewData.purchaseSumTon * 100)"
            striped
            striped-flow />
        </el-descriptions-item>
      </el-descriptions>
      <div>
        <el-divider />
        <Table
          :data="tableData"
          v-loading="tableLoading"
          :misStripe="true"
          :row-style="rowStyle">
          <el-table-column
            type="index"
            width="60"
            label="编号"
            :resizable="false" />
          <el-table-column
            label="类型"
            :resizable="false">
            <template #default="scope">
              {{ purchaseNodeType[scope.row.nodeTypeEnum] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="nodeRelationName"
            label="名称"
            :resizable="false" />
          <el-table-column
            label="预付款日期"
            :resizable="false">
            <template #default="scope">
              <el-date-picker
                v-if="scope.row.nodeTypeEnum !== Object.keys(purchaseNodeType)[0]"
                v-model="scope.row.firstPayDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="预付款日期" />
            </template>
          </el-table-column>
          <el-table-column
            label="尾款日期"
            :resizable="false">
            <template #default="scope">
              <el-date-picker
                v-if="scope.row.nodeTypeEnum !== Object.keys(purchaseNodeType)[0]"
                v-model="scope.row.endPayDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="尾款日期" />
            </template>
          </el-table-column>
        </Table>
        <el-divider />
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          :label-width="config.form.label.width"
          status-icon>
          <el-row>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="车次号"
                prop="trainNumber">
                <el-input
                  v-model="formData.trainNumber"
                  placeholder="车次号"></el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="商品名称"
                prop="baseRiceBarnGoodsId">
                <el-select
                  v-model="formData.baseRiceBarnGoodsId"
                  placeholder="商品名称"
                  clearable>
                  <el-option
                    v-for="item in baseRiceBarnGoodsList"
                    :key="item.id"
                    :disabled="item.disabled"
                    :label="item.simple_name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="实际米厂单价(元/吨)"
                prop="realRiceFactoryUnitPrice">
                <el-input-number
                  v-model="formData.realRiceFactoryUnitPrice"
                  controls-position="right"
                  :min="0">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="发货吨数(吨)"
                prop="sendTon">
                <el-input-number
                  v-model="formData.sendTon"
                  controls-position="right"
                  :min="0">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="到货完整吨数(吨)"
                prop="arriveIntactTon">
                <el-input-number
                  v-model="formData.arriveIntactTon"
                  controls-position="right"
                  :min="0">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="到货破损吨数(吨)"
                prop="arriveWornTon">
                <el-input-number
                  v-model="formData.arriveWornTon"
                  controls-position="right"
                  :min="0">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="到货日期"
                prop="arriveDate">
                <el-date-picker
                  v-model="formData.arriveDate"
                  type="date"
                  style="width: 150px;"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="到货日期" />
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="提货预计结束日期"
                prop="pickPredictFinishDate	">
                <el-date-picker
                  v-model="formData.pickPredictFinishDate"
                  :disabled-date="disabledDate"
                  style="width: 150px;"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="预计结束日期" />
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="启用状态"
                prop="isEnable">
                <el-select
                  v-model="formData.isEnable"
                  placeholder="启用状态"
                  clearable>
                  <el-option
                    :label="config.button.text.enable"
                    :value="true" />
                  <el-option
                    :label="config.button.text.stop"
                    :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="route.query.id && route.query.purchaseOrderNumber"
              :span="6"
              class="el_col_fit">
              <el-form-item
                label="是否完成提货"
                prop="isFinish">
                <el-switch
                  v-model="formData.isFinish"
                  class="ml-2"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
              </el-form-item>
            </el-col>
            <el-col
              :span="24"
              class="el_col_fit">
              <el-form-item label="附件">
                <UploadFile
                  ref="uploadRef"
                  :show="true"
                  :file-uuids="fileDataList"
                  @success="success"
                  @delete-file="deleteFile" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="button">
            <el-button
              @click="router.back()">
              {{ config.button.text.close }}
            </el-button>
            <el-button
              v-if="!route.query.id"
              type="info"
              @click="addEvent">
              {{ config.button.text.add }}
            </el-button>
            <el-button
              v-else
              type="warning"
              @click="editEvent">
              {{ config.button.text.edit }}
            </el-button>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <SelectPurchaseBatch
      ref="selectPurchaseBatchRef"
      @save="save" />
  </div>
  <!-- 手机端页面 -->
  <H5Index v-else></H5Index>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Table from "@/components/Table.vue"
import message from "@/common/element-plus/message";
import config from "@/common/element-plus/config";
import ApiPurchaseOrderNode from "@/api/modules/purchase-order-node"
import ApiPurchaseOrder from "@/api/modules/purchase-order"
import ApiBaseRiceBarnGoods from "@/api/modules/base-rice-barn-goods"
import ApiTrainRepertory from "@/api/modules/train-repertory"
import ApiTrainRepertoryNode from "@/api/modules/train-repertory-node"
import SelectPurchaseBatch from "./component/SelectPurchaseBatch.vue"
import { useAppStore } from "@/stores/app"
import { formatDate } from "@/common/utils/date";
import { purchaseNodeType } from "@/common/enum/purchase-order";
import { useValidator } from "@/hooks/useValidator";
import { useRoute, useRouter } from "vue-router"
import UploadFile from "@/components/UploadFile.vue"
import H5Index from "./H5Index.vue";
import confirm from "@/common/element-plus/confirm";

// 路由
const route = useRoute()
const router = useRouter()
// 选择订单实例
const selectPurchaseBatchRef = ref()
// 附件回显
const fileDataList = ref([]);
// 表单实例
const formRef = ref()
// 表单
const formData = ref({})
const viewData = ref({})
const appStore = useAppStore()
// 表格
const tableData = ref([])
const tableLoading = ref(false)
// 商品简称列表
const baseRiceBarnGoodsList = ref([])

const { required, validate } = useValidator()

// 校验
const formRules = {
  trainNumber: [required("车次号")],
  sendTon: [required("发货吨数")],
  arriveIntactTon: [required("到货完整吨数")],
  arriveWornTon: [required("到货破损吨数")],
  isEnable: [required("启用状态", "change")],
}

// 选择订单
const selectPurchaseBatch = () => {
  selectPurchaseBatchRef.value.visibility = true
}

// 选择订单回调
const save = async (data) => {
  viewData.value = data
  formData.value.isFinish = false
  formData.value.purchaseOrderName = viewData.value.purchaseOrderName
  formData.value.purchaseOrderNumber = viewData.value.purchaseOrderNumber
  formData.value.arriveWornTon = 0
  formData.value.arriveIntactTon = 0
  formData.value.sendTon = 0
  await getListNodeByPurchaseOrderNumber()
  await getPurchaseArriveTonByPurchaseOrderNumber()
  getCurrentTime()
  message.success()
}

// 通过采购订单uuid获取全部节点信息
const getListNodeByPurchaseOrderNumber = async () => {
  tableLoading.value = true
  const data = await ApiPurchaseOrderNode.getListNodeByPurchaseOrderNumber({
    purchaseOrderNumber: viewData.value.purchaseOrderNumber
  })
  tableData.value = data.data
  tableLoading.value = false
}

// 通过 采购订单编号 统计到货吨数
const getPurchaseArriveTonByPurchaseOrderNumber = async () => {
  const data = await ApiTrainRepertory.getPurchaseArriveTonByPurchaseOrderNumber({
    purchaseOrderNumber: viewData.value.purchaseOrderNumber
  })
  viewData.value.tonnageArrived = data.data
}

// 修改
const editEvent = async () => {
  await validate(formRef.value)
  const data = await confirm.submit()
  if (data !== "confirm") return
  await ApiTrainRepertory.update({
    trainRepertory: formData.value,
    trainRepertoryNodeList: tableData.value
  })
  await getPurchaseArriveTonByPurchaseOrderNumber()
  message.success()
}

// 获取当前日期
const getCurrentTime = () => {
  if (!formData.value.arriveDate) {
    const now = new Date();
    const year = now.getFullYear();
    let month = now.getMonth() + 1;
    let date = now.getDate();
    if (month < 10) {
      month = "0" + month;
    }
    if (date < 10) {
      date = "0" + date;
    }
    formData.value.arriveDate = `${year}-${month}-${date}`
  }
}

// 新增
const addEvent = async () => {
  await validate(formRef.value)
  const data = await confirm.submit()
  if (data !== "confirm") return
  await ApiTrainRepertory.insert({
    trainRepertory: formData.value,
    nodeInsertDtoList: tableData.value.map(item => {
      return {
        purchaseOrderNodeUuid: item.nodeUuid,
        firstPayDate: item.firstPayDate,
        endPayDate: item.endPayDate
      }
    })
  })
  await getPurchaseArriveTonByPurchaseOrderNumber()
  message.success()
  formData.value.trainNumber = ""
  formData.value.arriveDate = ""
  formData.value.pickPredictFinishDate = ""
  formData.value.baseRiceBarnGoodsId = ""
  formData.value.sendTon = ""
  formData.value.realRiceFactoryUnitPrice = ""
  formData.value.arriveIntactTon = ""
  formData.value.arriveWornTon = ""
  formData.value.isFinish = false
  tableData.value.forEach(item => {
    item.firstPayDate = ""
    item.endPayDate = ""
  })
}

// 更改行背景色
const rowStyle = ({ row }) => {
  if (row.nodeTypeEnum.startsWith("BASE_")) {
    return { backgroundColor: "#f4fdee" }
  }
  return { backgroundColor: "#d9ddd9" };
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() < new Date(formData.value.arriveDate).getTime()
}

// 获取单个采购订单
const queryOneByPurchaseOrderNumber = async () => {
  const data = await ApiPurchaseOrder.queryOneByPurchaseOrderNumber({ purchaseOrderNumber: route.query.purchaseOrderNumber })
  viewData.value = data.data
  formData.value.purchaseOrderName = viewData.value.purchaseOrderName
  formData.value.purchaseOrderNumber = viewData.value.purchaseOrderNumber
}

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

onMounted(async () => {
  if (appStore.isPhone) return
  const data = await ApiBaseRiceBarnGoods.getSimpleNameList("/baseRiceBarnGoods/")
  baseRiceBarnGoodsList.value = data.data
  setTimeout(async () => {
    if (!route.query.id && !route.query.purchaseOrderNumber) {
      if (!appStore.isPhone && selectPurchaseBatchRef.value) {
        selectPurchaseBatchRef.value.visibility = true
      }
    } else if (!route.query.id) {
      await queryOneByPurchaseOrderNumber()
      await getListNodeByPurchaseOrderNumber()
      await getPurchaseArriveTonByPurchaseOrderNumber()
      formData.value.isFinish = false
    } else {
      let data = await ApiTrainRepertory.selectTrainRepertoryById({ id: route.query.id })
      formData.value = data.data
      const find = baseRiceBarnGoodsList.value.find(item => item.id === formData.value.baseRiceBarnGoodsId)
      if (!find) baseRiceBarnGoodsList.value.push({
        simple_name: formData.value.baseRiceBarnGoodsSimpleName + "(已禁用)",
        id: formData.value.baseRiceBarnGoodsId,
        disabled: true
      })
      fileDataList.value = []
      if (formData.value.fileDataJson && Array.isArray(JSON.parse(formData.value.fileDataJson))) {
        fileDataList.value = JSON.parse(formData.value.fileDataJson);
      }
      await queryOneByPurchaseOrderNumber()
      data = await ApiTrainRepertoryNode.selectListByTrainRepertoryId({
        trainRepertoryId: route.query.id
      })
      tableData.value = data.data
      await getPurchaseArriveTonByPurchaseOrderNumber()
    }
  }, 200)
  getCurrentTime()
  formData.value.isEnable = true
})
</script>

<style lang="scss" scoped>
.train_inventory_insert {
  .el-card {
    height: calc(100vh - 90px);
  }

  .select_order {
    margin-bottom: 10px;
  }

  .button {
    justify-content: center;
    align-items: center;
  }

  :deep(.el-descriptions__label) {
    width: 110px;
  }

  .el-input-number {
    width: 150px;
  }

  .el-select {
    width: 150px;
  }

  .el-input {
    width: 150px;
  }
}
</style>